package com.neshai.webapp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.neshai.webapp.entity.Invoices;
import com.neshai.webapp.entity.User;
import com.neshai.webapp.mapper.InvoicesMapper;
import com.neshai.webapp.mapper.UserMapper;
import com.neshai.webapp.service.InvoicePaymentSuccessService;
import com.neshai.webapp.utils.R;
import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import io.jsonwebtoken.Claims;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.JsonSyntaxException;
import com.stripe.exception.SignatureVerificationException;
import com.stripe.model.*;
import com.stripe.net.Webhook;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class StripeController {

    @Value("${stripe.endpointSecret}")
    String endpointSecret;
    @Value("${stripe.apikey}")
    String stringApiKey;

    private final InvoicePaymentSuccessService invoicePaymentSuccessService;

    private final InvoicesMapper invoicesMapper;

    private final UserMapper userMapper;

    @PostConstruct
    public void init() {
        Stripe.apiKey = stringApiKey;
    }

    @RequestMapping({"/cancelSubscription"})
    public R cancelSubscription(HttpServletRequest request) throws StripeException {
        Object claimsObject = request.getAttribute("claims");
        if (claimsObject instanceof Claims) {
            String email = (String) ((Claims) claimsObject).get("email");
            List<Invoices> list = invoicesMapper.selectList(
                    new QueryWrapper<Invoices>().eq("customer_email", email).select("invoice")
            );
            userMapper.update(
                    new UpdateWrapper<User>().eq("email", email).set("subscription_status", 2)
            );

            if (!list.isEmpty()) {
                Invoice invoice = Invoice.retrieve(list.getFirst().getInvoice());
                // 获取订阅编号
                String subscriptionId = invoice.getSubscription();
                //String subscriptionId = "sub_1PobPj2LVWfSov9xUAvUvwlP";
                try {
                    // 获取当前的订阅对象
                    Subscription subscription = Subscription.retrieve(subscriptionId);
                    // 创建请求参数，取消“在周期结束时取消”的操作
                    Map<String, Object> params = new HashMap<>();
                    params.put("cancel_at_period_end", true);  // 取消订阅在周期结束时取消的操作
                    // 更新订阅
                    Subscription updatedSubscription = subscription.update(params);
                    return R.success("cancel success");
                } catch (StripeException e) {
                    return R.fail("The subscription has been cancelled");
                }
            }
        } else {
            return R.fail("The subscription has been cancelled");
        }
        return R.fail("The subscription has been cancelled");
    }

    @RequestMapping({"/updatedSubscription"})
    public R updatedSubscription(HttpServletRequest request) throws StripeException {

        Object claimsObject = request.getAttribute("claims");
        if (claimsObject instanceof Claims) {
            String email = (String) ((Claims) claimsObject).get("email");
            List<Invoices> list = invoicesMapper.selectList(
                    new QueryWrapper<Invoices>().eq("customer_email", email).select("invoice")
            );
            userMapper.update(
                    new UpdateWrapper<User>().eq("email", email).set("subscription_status", 1)
            );
            if (!list.isEmpty()) {
                Invoice invoice = Invoice.retrieve(list.getFirst().getInvoice());
                // 获取订阅编号
                String subscriptionId = invoice.getSubscription();
                //String subscriptionId = "sub_1PobPj2LVWfSov9xUAvUvwlP";
                try {
                    // 获取当前的订阅对象
                    Subscription subscription = Subscription.retrieve(subscriptionId);
                    // 创建请求参数，取消“在周期结束时取消”的操作
                    Map<String, Object> params = new HashMap<>();
                    params.put("cancel_at_period_end", false);  // 取消订阅在周期结束时取消的操作
                    // 更新订阅
                    Subscription updatedSubscription = subscription.update(params);

                    return R.success("cancel success");
                } catch (StripeException e) {

                    return R.fail("The subscription has been cancelled");
                }
            }
        } else {
            return R.fail("The subscription has been cancelled");
        }
        return R.fail("The subscription has been cancelled");
    }

    @RequestMapping({"/webhook"})
    public String stripeWebhook(HttpServletRequest request, HttpServletResponse response, @RequestBody String payload) {
        String sigHeader = request.getHeader("Stripe-Signature");
        Event event = null;
        try {
            event = Webhook.constructEvent(
                    payload, sigHeader, endpointSecret
            );
        } catch (JsonSyntaxException e) {
            // Invalid payload
            response.setStatus(400);
            return "";
        } catch (SignatureVerificationException e) {
            // Invalid signature
            response.setStatus(400);
            return "";
        }
        EventDataObjectDeserializer dataObjectDeserializer = event.getDataObjectDeserializer();
        StripeObject stripeObject = null;
        if (dataObjectDeserializer.getObject().isPresent()) {
            stripeObject = dataObjectDeserializer.getObject().get();
        } else {
            // Deserialization failed, probably due to an API version mismatch.
            // Refer to the Javadoc documentation on `EventDataObjectDeserializer` for
            // instructions on how to handle this case, or return an error here.
        }
        // Handle the event

        String eventType = event.getType();

        switch (eventType) {
//            case "payment_intent.succeeded":
//                // 如果事件是 payment_intent.succeeded，获取 PaymentIntent 对象
//                PaymentIntent paymentIntent = (PaymentIntent) event.getDataObjectDeserializer().getObject().orElse(null);
//                if (paymentIntent != null) {
//                    String paymentId = paymentIntent.getId();
//                    long amount = paymentIntent.getAmount();
//                    String currency = paymentIntent.getCurrency();
//                    String customer = paymentIntent.getCustomer();
//                    String description = paymentIntent.getDescription();
//
//                    // 输出信息
//                    System.out.println("Payment ID: " + paymentId);
//                    System.out.println("Amount: " + amount);
//                    System.out.println("Currency: " + currency);
//                    System.out.println("Customer: " + customer);
//                    System.out.println("Description: " + description);
//                    System.out.println(paymentIntent.getReceiptEmail());
//                }
//                break;
            case "invoice.payment_succeeded":
                // 如果事件是 invoice.payment_succeeded，获取 Invoice 对象
                invoicePaymentSuccessService.handleInvoicePaymentSuccess(event);
                break;
            // 处理其他事件类型...
            //case "customer.subscription.created":

            default:
                System.out.println("Unhandled event type: " + eventType);
        }
        response.setStatus(200);
        return "";
    }

//    @RequestMapping({"/createLink"})
//    public PaymentIntent createLink(HttpServletRequest request, HttpServletResponse response, @RequestBody String payload) throws StripeException {
////        PaymentIntentCreateParams params =
////                PaymentIntentCreateParams.builder()
////                        .setAmount(2000L) // 金额，以分为单位
////                        .setCurrency("usd") // 货币
////                        .addPaymentMethodType("card") // 支付方式
////                        .setReceiptEmail("qweqr@gmail.com")
////                        .build();
////
////        PaymentIntent paymentIntent = PaymentIntent.create(params);
////        return paymentIntent;
//        Stripe.apiKey = "sk_test_51Pl2IR2LVWfSov9xP4nNQzn7oFtbKLlM7ZUhEnuTOxql3pccnWpgaJUvCvqqZ62LZL59UNyVUMSaLLnJxieXgPnf00BtlA5yyK";
//
//
//        PaymentLinkCreateParams params =
//                PaymentLinkCreateParams.builder()
//                        .addLineItem(
//                                PaymentLinkCreateParams.LineItem.builder()
//                                        .setPrice("{{PRICE_ID}}")
//                                        .setQuantity(1L)
//                                        .build()
//                        )
//                        .setAfterCompletion(
//                                PaymentLinkCreateParams.AfterCompletion.builder()
//                                        .setType(PaymentLinkCreateParams.AfterCompletion.Type.REDIRECT)
//                                        .setRedirect(
//                                                PaymentLinkCreateParams.AfterCompletion.Redirect.builder()
//                                                        .setUrl("https://example.com")
//                                                        .build()
//                                        )
//                                        .build()
//                        )
//                        .build();
//
//
//        PaymentLink paymentLink = PaymentLink.create(params);
//    }
}
